package com.bootdo.order.task;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.ExceptionUtils;
import com.bootdo.merchant.dao.MerchantDao;
import com.bootdo.merchant.domain.MerchantDO;
import com.bootdo.order.dao.OrderDao;
import com.bootdo.order.domain.OrderDO;
import com.bootdo.order.utils.HttpClientUtil;
import com.bootdo.order.utils.MD5SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @program: bootdo
 * @packageName: com.bootdo.order
 * @className: OrderCallBackTask
 * @description: 根据订单状态自动回调通知
 * @create: 2020-03-04 21:01
 */
@Component
@Configuration
@EnableScheduling
public class OrderCallBackTask {

    private Logger logger = LoggerFactory.getLogger(OrderCallBackTask.class);

    @Autowired      //注入mapper
    @SuppressWarnings("all")
    private OrderDao orderMapper;

    @Autowired      //注入mapper
    @SuppressWarnings("all")
    private MerchantDao merchantMapper;


    /**
     * 功能描述:根据订单状态自动回调通知
     * @param
     * @Return: void
     * @Date: 2020/3/4 21:03
     */
    @Lazy(value = false)
    @Scheduled(cron = "0/30 * * * * ?")
    public void orderCallBack(){
        logger.debug("开始执行任务调度，获取待回调订单信息信息" + DateUtils.formatDateTime(new Date()));
        List<OrderDO> list = orderMapper.getOrderByCallBackStatus();
        if (list!=null && list.size() > 0 ){
            for (OrderDO order : list) {
                String url = order.getNotifyUrl();
                Map<String, String> params = new HashMap<>();
                params.clear();
                long requestTime = System.currentTimeMillis();
                MerchantDO merchant = merchantMapper.getByIdent(order.getIdentification());
                if (merchant != null) {
                    //支付类型
                    params.put("payType", order.getPayType() + "");
                    //实际支付金额
                    params.put("actualMoney", order.getActualMoney() + "");
                    //订单金额
                    params.put("money", order.getMoney() + "");
                    //平台订单号
                    params.put("billNo", order.getId() + "");
                    //商户自定义订单号
                    params.put("orderNo", order.getOrderNo());
                    //商户token
                    params.put("token", merchant.getToken());
                    params.put("identification", merchant.getIdentification());
                    params.put("requestTime", requestTime + "");
                    Map<String, String> signMap = new HashMap<>();
                    signMap.put("requestTime", requestTime + "");
                    signMap.put("token", merchant.getToken());
                    signMap.put("identification", merchant.getIdentification());
                    signMap.put("payType", order.getPayType() + "");
                    String sign = MD5SignUtil.sign(signMap);
                    logger.debug("<============调用线程请求地址============>" + url);
                    logger.debug("<============调用线程请求参数============>" + JSONObject.toJSONString(params));
                    try {
                        String rJson = HttpClientUtil.httpPost(url, params, sign);
                        if ("success".equalsIgnoreCase(rJson)){
                            //回调成功
                            int res = orderMapper.updateCallBackStatus(order);
                            logger.debug("<============调用线程回调成功============>：" + order.getOrderNo() + "，支付类型："+order.getPayType() + "，更新状态："+res);
                        } else {
                            //回调失败
                            logger.error("<============调用线程回调失败============>：" + order.getOrderNo() + "，支付类型："+order.getPayType()+"，回调返回值"+rJson);
                        }
                        orderMapper.updateCallBackNumber(order);
                    } catch (Exception e) {
                        e.printStackTrace();
                        //回调失败
                        logger.error("<============调用线程回调失败============>：" + order.getOrderNo() + "，支付类型："+order.getPayType()+"，失败原型"+ ExceptionUtils.getStackTraceAsString(e));
                    }

                }
            }
        }
    }

}
